package com.yuyu.storage.domin.Do;

import com.yuyu.commons.factory.RepositoryFactory;
import com.yuyu.storage.domin.repository.StockRepository;
import com.yuyu.storage.infrastructure.general.cache.StockCache;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author
 * @version 1.0
 * @description: 商品库存DO
 * @date 2022/8/10 14:35
 */
@Data
@Accessors(chain = true)
public class GoodsStockDO implements Serializable {

    private static final StockRepository stockRepository = RepositoryFactory.get(StockRepository.class);
    private static final StockCache stockCache = RepositoryFactory.get(StockCache.class);

    private Long goodsId; //商品id

    private Long stockNum; //商品库存

    /**
     * 查询库存
     * @param goodsId
     * @return
     */
    public Long getStockNum(Long goodsId){
        if (Objects.nonNull(goodsId)) {
            return stockRepository.getStockByGoodsId(goodsId);
        }
       throw new RuntimeException("商品id不能为null,查询商品库存失败");
    }

    /**
     * 扣减库存
     * @param activityId
     * @param stockNum
     * @return
     */
    public Boolean descStockNum(Long activityId, Long stockNum){
        if (Objects.nonNull(activityId) && Objects.nonNull(stockNum)){
          return  stockCache.decrStock(activityId, stockNum);
        }
        throw new RuntimeException("查询参数缺失,查询商品库存失败");
    }

    /**
     * 冻结库存
     * @param goodsId
     * @param frozenNum
     * @return
     */
    public void rollBackStock(Long goodsId,Long frozenNum){
        //增加缓存库存
        stockCache.increaseStock(goodsId,frozenNum);
        //增加db库存
        stockRepository.rollBackStock(goodsId,frozenNum);
    }
}
